package com.numbfish.ex_01_traditional;

import java.util.Random;

public class FXNewsProvider {
    private IFXNewsListener newsListener;
    private IFXNewsPersister newPersistener;
    private Random random;
    public FXNewsProvider()
    {   // 在构造函数中创建依赖
        // 主动获取依赖对象
        newsListener = new DowJonesNewsListener();
        newPersistener = new DowJonesNewsPersister();
    }
    public void getAndPersistNews()
    {
        String[] newsIds = newsListener.getAvailableNewsIds();
        if(ArrayUtils.isEmpty(newsIds))
        {
            return;
            }

        for(String newsId : newsIds)
        { FXNewsBean newsBean = newsListener.getNewsByPK(newsId);
            newPersistener.persistNews(newsBean);
            newsListener.postProcessIfNecessary(newsId);
            }
    }

    private class DowJonesNewsListener implements IFXNewsListener {
        @Override
        public String[] getAvailableNewsIds() {
            return new String[]{"张飞新闻"};
        }

        @Override
        public FXNewsBean getNewsByPK(String newsId) {
            int i = random.nextInt(1000);
            return new FXNewsBean(newsId,newsId+":"+i);
        }

        @Override
        public void postProcessIfNecessary(String newsId) {
            System.out.println("postProcessIfNecessary executed...");
        }
    }

    private class DowJonesNewsPersister implements IFXNewsPersister {
        @Override
        public void persistNews(FXNewsBean newsBean) {
            System.out.println("新闻内容保存");
        }
    }
}
